package com.bayihouse.aop;


import com.bayihouse.annotation.AuthCheck;
import com.bayihouse.common.ErrorCode;
import com.bayihouse.constant.AdministerConstant;
import com.bayihouse.exception.BusinessException;
import com.bayihouse.model.entity.Administer;
import com.bayihouse.service.AdministerService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@Aspect
@Component
public class PermissionCheckHandle {

    @Resource
    private AdministerService administerService;


    @Around("@annotation(permissionCheck)")
    public Object doHandle(ProceedingJoinPoint joinPoint, AuthCheck permissionCheck) throws Throwable {
        //获得最低权限的用户级别
        Integer leastRole = permissionCheck.mustRole();
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();

        HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();

        Administer loginUser = administerService.getLoginAdminister(request);

        Integer role = loginUser.getUserRole();

        if (leastRole > role) {
            throw new BusinessException(ErrorCode.FORBIDDEN_ERROR, "你没有此权限");
        }
        return joinPoint.proceed();
    }

}
